package com.ts.util;

import com.ts.entity.MonitorEntity;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

@Slf4j
public class FileUtil {
    public static int getSplitFile(File file,int size,String temp) {
        RandomAccessFile raf = null;
        int count = 0;
        try {
            //获取目标文件 预分配文件所占的空间 在磁盘中创建一个指定大小的文件   r 是只读
            raf = new RandomAccessFile(file, "r");
            long length = raf.length();//文件的总长度

            //如果余数为零
            int remainder = (int) (length%size);
            count = (int) (length / size);
            if(0!=remainder){
                count += 1;
            }
            long offSet = 0L;//初始化偏移量
            for (int i = 0; i < count - 1; i++) { //最后一片单独处理
                long begin = offSet;
                long end = (i + 1) * size;
                offSet = getWrite(file, temp,i, begin, end);
            }
            if (length - offSet > 0) {
                getWrite(file, temp,count-1, offSet, length);
            }

        } catch (FileNotFoundException e) {
            System.out.println("没有找到文件");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return count;
    }
    public static long getWrite(File file,String temp,int index,long begin,long end) {
        File tempFolder = new File(temp);
        if(!tempFolder.exists()){
            tempFolder.mkdirs();
        }
        long endPointer = 0L;
        try {
            //申明文件切割后的文件磁盘
            RandomAccessFile in = new RandomAccessFile(file, "r");
            //定义一个可读，可写的文件并且后缀名为.tmp的二进制文件
            RandomAccessFile out = new RandomAccessFile(new File(temp +File.separator+ file.getName().split("\\.")[0] + "_" + index + ".tmp"), "rw");

            //申明具体每一文件的字节数组
            byte[] b = new byte[1024];
            int n = 0;
            //从指定位置读取文件字节流
            in.seek(begin);
            //判断文件流读取的边界
            while (in.getFilePointer() <= end && (n = in.read(b)) != -1) {
                //从指定每一份文件的范围，写入不同的文件
                out.write(b, 0, n);
            }
            //定义当前读取文件的指针
            endPointer = in.getFilePointer();
            //关闭输入流
            in.close();
            //关闭输出流
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return endPointer;
    }

    /**
     *
     * @param
     */
    public static void merge(MonitorEntity monitorEntity){

        //生产文件名称：
        Integer mergeCount = monitorEntity.getCount();
        String fileName = "";
        String splitFileNamePre = "";

        //合并文件名称
        if(null!=monitorEntity.getUpperReceiveLowerFileName()){
            fileName = monitorEntity.getAbsUpperFolderPath() + File.separator + monitorEntity.getUpperReceiveLowerFileName();
            splitFileNamePre = monitorEntity.getAbsUpperFolderPath() + File.separator + monitorEntity.getLowerSendUpperFileName().split("\\.")[0];
        }else if(null!=monitorEntity.getLowerReceiveUpperFileName()){
            fileName = monitorEntity.getAbsLowerFolderPath() + File.separator + monitorEntity.getLowerReceiveUpperFileName();
            splitFileNamePre = monitorEntity.getAbsLowerFolderPath() + File.separator + monitorEntity.getUpperSendLowerFileName().split("\\.")[0];
        }
        merge(fileName, splitFileNamePre, mergeCount);
    }

    /**
     *
     * @param file 合并名称
     * @param source 切片前缀
     * @param tempCount 切片数量
     */
    public static void merge(String file,String source,int tempCount) {

        /**
         * 两个路径：
         *  切片路径
         *  生产文件路径
         */
        RandomAccessFile raf = null;
        try {
            //申明随机读取文件RandomAccessFile
            raf = new RandomAccessFile(new File(file), "rw");
            //开始合并文件，对应切片的二进制文件
            for (int i = 0; i < tempCount; i++) {
                //读取切片文件
                String filePath = source+"_"+ i + ".tmp";
                RandomAccessFile reader = new RandomAccessFile(new File(filePath), "r");
                byte[] b = new byte[1024];
                int n = 0;
                //先读后写
                while ((n = reader.read(b)) != -1) {//读
                    raf.write(b, 0, n);//写
                }
                reader.close();
            }

            //合并完成之后，删除切片
            for(int i=0;i<tempCount;i++){
                String filePath = source+"_"+ i + ".tmp";
                File tempFile = new File(filePath);
               tempFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
